package com.example.foobar.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.foobar.business.service.DidiService;
import com.example.foobar.dto.DidiURL;
import com.example.foobar.dto.DidiURLRequestDTO;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;

/**
 * 分析系统配置文件 服务实现类
 *
 * @author 郑英奔
 * @since 2021-05-31
 */
@Slf4j
@Service
public class DidiServiceImpl implements DidiService {

    public static String APPKEY = "chuangyun";
    public static String ACCESSKEY = "E8q02xENueq7zReykxPhbaysnGddqwXv";

    public static String inputStreamToString(InputStream inputStream) throws IOException {
        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    }

    public static String genSign(TreeMap<String, Object> header, TreeMap<String, Object> body, String accessKey) throws Exception {
        TreeMap<String, Object> params = new TreeMap<>();
        for (String key : header.keySet()) {
            params.put(key, header.get(key));
        }
        for (String key : body.keySet()) {
            params.put(key, body.get(key));
        }

        StringBuilder str = new StringBuilder();
        for (String key : params.keySet()) {
            str.append("&").append(key).append("=").append(params.get(key));
        }
        str = new StringBuilder(str.toString().replaceFirst("&", ""));
        System.out.println("1 str: " + str);
        str = new StringBuilder(URLEncoder.encode(str.toString(), String.valueOf(StandardCharsets.UTF_8)));
        System.out.println("2 str: " + str);
        str.append(accessKey);
        System.out.println("3 str: " + str);
        str = new StringBuilder(DigestUtils.shaHex(str.toString().getBytes(StandardCharsets.UTF_8)));
        System.out.println("4 str: " + str);
        str = new StringBuilder(Base64.getEncoder().encodeToString(str.toString().getBytes(StandardCharsets.UTF_8)));
        System.out.println("5 str: " + str);
        str = new StringBuilder(URLEncoder.encode(str.toString(), String.valueOf(StandardCharsets.UTF_8)));
        System.out.println("6 str: " + str);
        return str.toString();
    }

    public DidiURL post(String urlPath, TreeMap<String, Object> header, TreeMap<String, Object> body, String accessKey) throws Exception {
        String sign = genSign(header, body, accessKey);

        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "application/json");//设置参数类型是json格式
        connection.setRequestProperty("Sign", sign);//设置参数类型是json格式
        for (String key : header.keySet()) {
            connection.setRequestProperty(key, header.get(key).toString());
        }
        connection.connect();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
        String json = new Gson().toJson(body);
        writer.write(json);
        writer.close();

        InputStream inputStream = connection.getInputStream();

        String rsult = inputStreamToString(inputStream);
        JSONObject parse = (JSONObject)JSON.parse(rsult);
        parse.get("data");
        DidiURL didiURL = JSON.toJavaObject((JSON) parse.get("data"), DidiURL.class);
        inputStream.close();
        return didiURL;
    }


    public static void get(String urlPath, TreeMap<String, Object> header, TreeMap<String, Object> param, String accessKey) throws Exception {
        String sign = genSign(header, param, accessKey);
        StringBuilder sb = new StringBuilder();
        sb.append(urlPath);
        sb.append("?");
        for (String key : param.keySet()) {
            sb.append("&").append(key).append("=").append(param.get(key));
        }

        String str = sb.toString().replaceFirst("&", "");
        URL url = new URL(str);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);

        connection.setRequestProperty("Sign", sign);//设置参数类型是json格式
        for (String key : header.keySet()) {
            connection.setRequestProperty(key, header.get(key).toString());
        }
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        System.out.println(inputStreamToString(inputStream));
        inputStream.close();
    }

//    public  void main(String[] args) throws Exception {
//        TreeMap<String, Object> header = new TreeMap<>();
//        header.put("Timestamp", (int) (System.currentTimeMillis() / 1000));
//        header.put("App-Key", APPKEY);
//
//        TreeMap<String, Object> body = new TreeMap<>();
//        //activity_id必须为数字类型
//        body.put("activity_id", 3026);
//        body.put("source_id", "1");
//        body.put("link_type", "h5");
//        //promotion_id必须为数字类型
//        body.put("promotion_id", "6858319240122325629");
//        //调用短链
//        post("https://union.didi.cn/openapi/v1.0/link/generate", header, body, ACCESSKEY);
//
//        //调用生成二维码
//        TreeMap<String, Object> param = new TreeMap<>();
//        param.put("dsi", "2178");
//        param.put("source_id", "1");
//        param.put("type", "h5");
////        get("https://union.didi.cn/openapi/v1.0/code/generate", header, param, ACCESSKEY);
//    }

    @Override
    public DidiURL getURL(DidiURLRequestDTO didiURLRequestDTO) throws Exception {

        TreeMap<String, Object> header = new TreeMap<>();
        header.put("Timestamp", (int) (System.currentTimeMillis() / 1000));
        header.put("App-Key", APPKEY);

        TreeMap<String, Object> body = new TreeMap<>();
        //activity_id必须为数字类型
        body.put("activity_id", Long.valueOf(didiURLRequestDTO.getActivityId()));
        body.put("source_id", didiURLRequestDTO.getSourceId());
        body.put("link_type", didiURLRequestDTO.getLinkType());
        //promotion_id必须为数字类型
        body.put("promotion_id", Long.valueOf(didiURLRequestDTO.getPromotionId()));
        //调用短链
        DidiURL post = post("https://union.didi.cn/openapi/v1.0/link/generate", header, body, ACCESSKEY);

        //调用生成二维码
        TreeMap<String, Object> param = new TreeMap<>();
        param.put("dsi", "2178");
        param.put("source_id", "1");
        param.put("type", "h5");

        return post;
    }
}
